package com.poetry.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.poetry.constant.RedisConstant;
import com.poetry.domain.dto.NotesDTO;
import com.poetry.domain.po.Notes;
import com.poetry.exception.BasePage;
import com.poetry.exception.R;
import com.poetry.mapper.NotesMapper;
import com.poetry.service.INotesService;
import com.poetry.util.UserContext;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class NotesServiceImpl extends ServiceImpl<NotesMapper, Notes>
        implements INotesService {
    @Override
    public R<Integer> addNotes(NotesDTO notesDTO) {
        Notes notes = new Notes();
        BeanUtils.copyProperties(notesDTO, notes);
        Integer userId = UserContext.getUserId();
        notes.setUserId(userId);
        boolean flag = this.save(notes);
        if (!flag) {
            return R.error("笔记添加失败");
        }
        return R.success("笔记添加成功", notes.getId());
    }

    @Override
    public R<List<Notes>> queryNotes(BasePage basePage) {
        // 页码
        int pageNum = basePage.getPageNum();
        // 页数
        int pageSize = basePage.getPageSize();
        Page<Notes> pageInfo = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Notes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Notes::getUpdateTime);
        queryWrapper.eq(Notes::getUserId, UserContext.getUserId());
        Page<Notes> page = this.page(pageInfo, queryWrapper);
        if (page.getTotal() == 0) {
            return R.error("笔记列表为空");
        }
        return R.success("获取笔记列表成功", pageInfo.getRecords());
    }

    @Override
    @Transactional
    public R<String> update(Notes notes) {
        Integer id = notes.getId();
        if (id == null) {
            return R.error("笔记id为空");
        }
        boolean flag = this.updateById(notes);
        if (!flag) {
            return R.error("笔记信息更新失败");
        }
        return R.success(null, "更新笔记信息成功");
    }

    @Override
    @Transactional
    public R<String> delete(Integer id) {
        boolean flag = this.removeById(id);
        if (!flag) {
            return R.error("笔记删除失败");
        }
        return R.success(null, "笔记删除成功");
    }
}
